﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using PSE.Framework.ErrorLogging;
using System.Diagnostics;
using PSE.Framework.UI.Resources;
using PSE.Framework.UI.Controls.SmartClient;
using System.IO;
using System.Reflection;
using PSE.Framework.Configuration;

namespace PSE.LogPackager.Application
{
    /// <summary>
    /// Interaction logic for LogPackager.xaml
    /// </summary>
    public partial class LogPackagerWindow : System.Windows.Window
    {
        public DateTime? DataInicial { get; set; }
        public DateTime? DataFinal { get; set; }

        public LogPackagerWindow()
        {
            InitializeComponent();
            ChangeIcon();

            this.DataContext = this;

            this.DataInicial = DateTime.Now.Date;
            this.DataFinal = DateTime.Now.Date;
        }

        private void btnEnviar_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            string title = (string)ResourceProviderManager.GetResourceProvider().TryGetResource("Infra.Controls.Label.TituloColetorEvidencias");

            try
            {
                if (!(dtInicial.Validate() && dtFinal.Validate()))
                    return;

                LogPackager logPackager = new LogPackager();
                string supportEmail = logPackager.SupportEmail;
                string packageFile = null;

                DateTime from = this.DataInicial.Value.Date;
                DateTime to = this.DataFinal.Value.Date;

                if (from.Date > to.Date)
                {
                    MessageBox.Show((string)ResourceProviderManager.GetResourceProvider().TryGetResource("Infra.Controls.Message.DataInicioMaiorDataFinal"), title, MessageBoxImage.Exclamation);
                    return;
                }

                // Coleta e empacota os arquivos
                packageFile = logPackager.Pack(ApplicationConfiguration.CurrentSystem, from, to);

                if (!string.IsNullOrEmpty(packageFile))
                {
                    string message = (string)ResourceProviderManager.GetResourceProvider().TryGetResource("Infra.Controls.Message.RelatorioErrosGeradoSucesso", packageFile, supportEmail);

                    if (MessageBox.Show(message, title, MessageBoxButton.OkCancel, MessageBoxImage.Information) == MessageBoxResult.Ok)
                    {
                        string subject = (string)ResourceProviderManager.GetResourceProvider().TryGetResource("Infra.Controls.Label.ColetarErros");
                        string body = (string)ResourceProviderManager.GetResourceProvider().TryGetResource("Infra.Controls.Message.AnexarRelatorioErros", packageFile);

                        // Codifica o assunto e o corpo do e-mail e troca o "+" (espaço) pelo código hexa
                        subject = System.Web.HttpUtility.UrlEncode(subject, Encoding.Default).Replace("+", Uri.HexEscape(' '));
                        body = System.Web.HttpUtility.UrlEncode(body, Encoding.Default).Replace("+", Uri.HexEscape(' '));

                        // Abrir e-mail
                        Process.Start(string.Format(@"mailto:{0}?subject={1}&body={2}", supportEmail, subject, body));
                    }
                }
                else
                {
                    MessageBox.Show((string)ResourceProviderManager.GetResourceProvider().TryGetResource("Infra.Controls.Message.NenhumErroEncontrado"), title, MessageBoxImage.Exclamation);
                }
            }
            catch (Exception ex)
            {
                ErrorLogger.WriteLog(LogType.Error, ex);

                MessageBox.Show((string)ResourceProviderManager.GetResourceProvider().TryGetResource("Infra.Controls.Message.NaoFoiPossivelGerarRelatorioErros"), title, MessageBoxImage.Error);
            }
        }

        private void btnCancelar_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            this.Close();
        }

        private void ChangeIcon()
        {
            MemoryStream memoryStream = new MemoryStream();
            PngBitmapDecoder pngBitmapDecoder;
            System.Drawing.Icon icon;
            Stream stream = null;

            Assembly entryAssembly = System.Reflection.Assembly.GetEntryAssembly();

            foreach (string resource in entryAssembly.GetManifestResourceNames())
            {
                if (resource.EndsWith(".ico"))
                {
                    stream = entryAssembly.GetManifestResourceStream(resource);
                    break;
                }
            }

            if (stream != null)
            {
                icon = new System.Drawing.Icon(stream);
                icon.ToBitmap().Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);

                memoryStream.Seek(0, SeekOrigin.Begin);

                pngBitmapDecoder = new PngBitmapDecoder(memoryStream, BitmapCreateOptions.None, BitmapCacheOption.Default);

                this.Icon = pngBitmapDecoder.Frames[0];
            }
        }
    }
}
